"use strict"
const crypto = require('crypto');

exports.format = {
    "id":'facebook',
    "name":"facebook H5(TOKEN自验证)",
    "sandbox":"https://graph.facebook.com",
    "production":"https://graph.facebook.com",
    "fields":{
        "appid" :{'type':'string','val':'','name':"AppId"},
        "secret" :{'type':'string','val':'','name':"AppSecret"},
        "access" :{'type':'string','val':'','name':"PAGE_ACCESS_TOKEN"}
    }
};
//登录与认证TOKEN
exports.login = function () {
    let token = this.get("token")
    if(!token){
        return this.error("token empty");
    }
    return Promise.resolve().then(()=>{
        return verify_facebook_token.call(this,token);
    }).then(ret=>{
        let openid = ret["player_id"];
        return openid;
    })
};
//关闭客户端
exports.logout = function () {
    this.output = 'text';
    //console.log("logout",this.req.method,JSON.stringify(this.req.body));
    if(this.req.method === "GET") {
        let challenge = this.get('hub.challenge')||'null';
        return this.success(challenge);
    }
    //正常响应 2131554733586442
    //let ttl = Date.now();
    //let message = this.model("facebook",this.opensdk["branch"]);
    let body = this.req.body;
    // Checks this is an event from a page subscription
    let recipient,playerid;
    if (body.object === 'page') {
        // Iterates over each entry - there may be multiple if batched
        for(let entry of body.entry) {
            // Gets the message. entry.messaging is an array, but
            // will only ever contain one message, so we get index 0
            let webhook_event = entry.messaging[0]||{};
            //console.log("facebook logout messaging",JSON.stringify(webhook_event));
            if( !webhook_event.sender || !webhook_event.sender.id || !webhook_event.game_play || !webhook_event.game_play.player_id){
                continue;
            }
            recipient = webhook_event.sender.id;
            playerid = webhook_event.game_play.player_id;   //openid
        };
        if(recipient && playerid){
            let sdk = this.opensdk["_id"];
            let data = {"sender":recipient};
            let openid = this.model("openid",this.opensdk["branch"])
            openid.logout(sdk,playerid,data,(err,ret)=>{
                //console.log("facebook logout",err,ret)
            });
        }
        // Returns a '200 OK' response to all requests
        return this.success('EVENT_RECEIVED');
    } else {
        // Returns a '404 Not Found' if event is not from a page subscription
        this.status = 404;
        return this.success('404 Not Found');
    }
};


exports.createOrder = function(config){
    let data = {};
    data["rmb"] = config['rmb'];
    data["attach"] = [config['attach'],config['orderid']].join('|');
    data["orderid"] = config['orderid'];
    return data;
}

//充值回调,sid|orderid
exports.orderNotify = function(){
    let token = this.get("token","string")
    if( !token ){
        return Promise.reject("token empty");
    }
    return Promise.resolve().then(()=>{
        return verify_facebook_token.call(this,token);
    }).then(ret=>{
        let str = String(ret["developer_payload"]);
        let arr = str.split('|');
        let orderid = arr.pop();
        let attach = arr.join('|');
        return {"attach":attach,"orderid":orderid}
    })
}
/**
 * @name orderResult
 * 包装游戏服发货信息
 */
exports.orderResult = function(err,ret){
    return err ? Promise.reject(err) : ret ;
}


function verify_facebook_token(token){
    if(!this.opensdk.setting || !this.opensdk.setting.secret){
        return Promise.reject("opensdk.setting.secret empty");
    }
    let arr = token.split(".");
    if(arr.length < 2){
        return Promise.reject("token.split.length error");
    }
    let data  = JSON.tryParse(base64_url_decode(arr[1]))
    if(!data){
        return  Promise.reject("payload_error");
    }
    let hmac = crypto.createHmac('sha256', this.opensdk.setting.secret);
    hmac.update(arr[1]);
    let rsig = hmac.digest('base64');
    if(arr[0] !== base64_url_encode(rsig)){
        return  Promise.reject("sign_error");
    }
    return data;
}





function base64_url_decode($input) {
    $input = $input.replace(/-/g, '+');
    $input = $input.replace(/_/g, '/');
    return new Buffer($input, 'base64').toString();
}

function base64_url_encode($input) {
    $input = $input.replace(/\//g,'_');
    $input = $input.replace(/\+/g,'-');
    return $input.replace(/=/g,'');
}